// main.cpp - HarmonyOS版本
// ⚠️ 注意：HarmonyOS 上必须使用 qtmain() 而不是 main()！

#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QSurfaceFormat>
#include <QtQml>
#include <QDebug>
#include <QGuiApplication>
#include <QCoreApplication>
#include <QOpenGLContext>
#include <QQuickWindow>
#include <QQuickItem>

#include "carousel3dview.hpp"
#include "interactiveimageitem.hpp"

// 全局对象实例（静态变量，确保生命周期）
static QQmlApplicationEngine *g_engine = nullptr;

extern "C" int qtmain(int argc, char **argv)
{
    // 防止重复初始化
    if (g_engine != nullptr) {
        qDebug() << "Carousel3DView Qt引擎已初始化，跳过重复初始化";
        return 0;
    }
    
    qDebug() << "Carousel3DView 开始初始化Qt应用...";
    
    // ========================================
    // Step 0: 创建 Qt 应用实例
    // ========================================
    QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);
    QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
    
    qputenv("QSG_INFO", "1");

    QGuiApplication app(argc, argv);
    QCoreApplication::setApplicationName(QStringLiteral("Carousel3DView"));
    QCoreApplication::setOrganizationName(QStringLiteral("Carousel3DView"));
    QCoreApplication::setOrganizationDomain(QStringLiteral("carousel3dview.com"));
    
    // ========================================
    // Step 1: 配置 OpenGL ES 表面格式
    // ========================================
    QSurfaceFormat format;
    format.setAlphaBufferSize(8);
    format.setRedBufferSize(8);
    format.setGreenBufferSize(8);
    format.setBlueBufferSize(8);
    format.setDepthBufferSize(24);
    format.setStencilBufferSize(8);
    format.setRenderableType(QSurfaceFormat::OpenGLES);
    format.setVersion(2, 0);
    format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
    format.setSamples(0);
    
    QSurfaceFormat::setDefaultFormat(format);
    qDebug() << "Carousel3DView Using OpenGLES version:" << format.majorVersion() << "." << format.minorVersion();
    
    // ========================================
    // Step 2: 注册 QML 类型和创建全局对象
    // ========================================
    // 注意：QWidget 在 QML 中需要特殊处理
    // 这里注册为单例类型，通过上下文属性访问
    qmlRegisterSingletonType<Carousel3DView>("Carousel3DView", 1, 0, "Carousel3DView",
        [](QQmlEngine *engine, QJSEngine *scriptEngine) -> QObject * {
            Q_UNUSED(engine)
            Q_UNUSED(scriptEngine)
            // 注意：这里需要创建一个父对象，但由于是单例，暂时使用 nullptr
            // 实际使用时可能需要调整
            return new Carousel3DView();
        });
    qDebug() << "Carousel3DView QML类型注册成功";
    
    // ========================================
    // Step 3: 创建并配置 QML 引擎
    // ========================================
    g_engine = new QQmlApplicationEngine();
    
    g_engine->addImportPath(QStringLiteral("qrc:/"));
    g_engine->addImportPath(QStringLiteral("qrc:/qml"));
    
    // 加载 QML 文件
    qDebug() << "Carousel3DView 加载QML文件: qrc:/main.qml";
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(g_engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    g_engine->load(url);
    
    // 兜底处理
    if (g_engine->rootObjects().isEmpty()) {
        qWarning() << "Carousel3DView QQmlApplicationEngine failed to load component. Fallback UI will be shown.";
        static const char fallbackQml[] =
            "import QtQuick 2.15\n"
            "Rectangle {\n"
            "  anchors.fill: parent\n"
            "  color: \"#FF0000\"\n"
            "  Text { anchors.centerIn: parent; color: \"white\"; text: \"QML加载失败\"; font.pixelSize: 20 }\n"
            "}\n";
        g_engine->loadData(QByteArray(fallbackQml), QUrl(QStringLiteral("qrc:/fallback.qml")));
        if (g_engine->rootObjects().isEmpty()) {
            qCritical() << "Carousel3DView Fallback UI also failed to load. Exiting.";
            return -1;
        }
    } else {
        qDebug() << "Carousel3DView QML文件加载成功";
    }

    // 进入事件循环
    return app.exec();
}

// 提供一个前向到 qtmain() 的适配
extern "C" int main(int argc, char **argv)
{
    return qtmain(argc, argv);
}
